import {
  queryStudentList,
  addStudentList,
  removeStudentList,
  updateStudentList,
  queryStudentDetail,
} from '@/services/api';

export default {
  namespace: 'students',

  state: {
    data: {
      list: [],
      pagination: {},
    },
    profile: {},
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryStudentList, payload);

      yield put({
        type: 'query',
        payload: response,
      });
    },

    *add({ payload, callback }, { call, put }) {
      const response = yield call(addStudentList, payload);

      yield put({
        type: 'query',
        payload: response,
      });
      if (callback) callback();
    },

    *remove({ payload, callback }, { call, put }) {
      const response = yield call(removeStudentList, payload);

      yield put({
        type: 'query',
        payload: response,
      });
      if (callback) callback();
    },

    *update({ payload, callback }, { call, put }) {
      const response = yield call(updateStudentList, payload);

      yield put({
        type: 'query',
        payload: response,
      });
      if (callback) callback();
    },

    *fetchByKey({ payload, callback }, { call, put }) {
      const response = yield call(queryStudentDetail, payload);

      yield put({
        type: 'queryOne',
        payload: response,
      });

      if (callback) callback();
    },
  },

  reducers: {
    query(state, { payload }) {
      return {
        ...state,
        data: payload,
      };
    },
    queryOne(state, { payload }) {
      return {
        ...state,
        profile: payload,
      };
    },
  },
};
